﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyRunDataBase;
using System.Windows.Threading;
using System.Device.Location;
using System.Windows.Navigation;
using BryhtControls;
using Microsoft.Phone.Info;
using BryhtCommon;
using System.Reflection;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Imaging;
using MyRun.Controls;

namespace MyRun
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Brush BrushRed
        {
            get
            {
                return new SolidColorBrush(Colors.Red);
            }
        }

        private Brush BrushDefaultFore
        {
            get
            {
                return Application.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush;
            }
        }

        private DateTime startTime;
        private TimeSpan durationTime = new TimeSpan(0);
        private TimeSpan pauseTime = new TimeSpan(0);
        private GeoCoordinateWatcher geo;
        private SportModel sportModel;
        private MyRunDataContent feetDB;
        private DispatcherTimer timer;
        private Point beforePoint;

        public MainPage()
        {
            InitializeComponent();

            JudgeLocationOn();

            if (ApproachHelper.JudgeFirstRun() == true)
            {
                ApproachHelper.ShowApproach(() =>
                {
                    this.ApplicationBar.IsVisible = true;
                });
                this.ApplicationBar.IsVisible = false;

            }
            else
            {
                this.ApplicationBar.IsVisible = true;
            }
        }

        //判断Location是否开启
        private bool JudgeLocationOn()
        {
            if (Isolated.Get("IsLocationOn") == null || Isolated.Get("IsLocationOn").ToString() == "false")
            {
                if (MessageBoxResult.OK == MessageBox.Show("我的跑步在运行的过程中需要使用您的位置信息，如果您确定使用本软件，我们会记录你的运动路线，记录的信息会存储在本地手机，未经过您的允许不会上传到任何服务，请您先确定同意我们获取您的位置信息。", "提示", MessageBoxButton.OK))
                {
                    Isolated.Set("IsLocationOn", "true");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                if (PhoneApplicationService.Current.ApplicationIdleDetectionMode == IdleDetectionMode.Enabled)
                {
                    //使锁屏运行
                    PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
                }
                RunInitial();
            }

            base.OnNavigatedTo(e);

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (geo != null)
            {
                var result = MessageBox.Show("确定不保存本条记录就退出吗？", "提示", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        //首次开始
        private void SportRunButton_Begin(object sender, EventArgs e)
        {
            sportModel = new SportModel();
            beforePoint = new Point(0, 0);
            startTime = DateTime.Now;
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(10000000);//定时器间隔为1秒
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            geo = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            geo.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(geo_StatusChanged);
            geo.MovementThreshold = 5;//5米一定位
            geo.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(geo_PositionChanged);
            geo.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            //时间
            durationTime = DateTime.Now - startTime;
            txtTimeHour.Text = durationTime.Hours.ToString();
            txtTimeMinuter.Text = durationTime.Minutes.ToString();
            txtTimeSecond.Text = durationTime.Seconds.ToString();
            if (geo == null)
            {
                return;
            }
            //速度
            if (geo.Position.Location.Speed.Equals(double.NaN))
            {
                sportModel.Speed = 0;
            }
            else
            {
                sportModel.Speed = geo.Position.Location.Speed * 3.6;//换算成千米每小时
            }
            //距离
            //sportModel.Distance += sportModel.Speed / 3600.0;
            txtDistance.Text = sportModel.Distance.ToString("0.00") + "公里";
            txtSpeed.Text = sportModel.Speed.ToString("0.00") + "公里/小时";
            txtCalorie.Text = sportModel.Calorie.ToString("0.00") + "Cal";

            if (geo.Status != GeoPositionStatus.Ready)//如果中途检测到未开启，则重新启动
            {
                geo.Start();
            }
            else if (geo.Position.Location.Speed.Equals(double.NaN))
            {
                geo.Start();
            }
        }

        void geo_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    txtGPS.Text = "位置服务未开启！";
                    txtGPS.Foreground = BrushRed;
                    break;
                case GeoPositionStatus.Initializing:
                    txtGPS.Text = "位置服务正在准备...";
                    txtGPS.Foreground = BrushRed;
                    break;
                case GeoPositionStatus.NoData:
                    txtGPS.Text = "位置服务获取数据失败！";
                    txtGPS.Foreground = BrushRed;
                    break;
                case GeoPositionStatus.Ready:
                    txtGPS.Text = "位置服务正常！";
                    txtGPS.Foreground = BrushDefaultFore;
                    break;
                default:
                    break;
            }
        }

        void geo_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {

            if (geo.Status == GeoPositionStatus.Ready)
            {
                //时间
                sportModel.Duration = durationTime.ToString();
                var speed = 0.0;
                if (e.Position.Location.Speed.Equals(double.NaN) == false)
                {
                    speed = e.Position.Location.Speed * 3.6;
                }
                if (speed == 0.0)//排除第一个无速度点
                {
                    if (feetDB.SportFoot.Count(p => p.SportId == sportModel.Id) == 0)
                    {
                        return;
                    }
                }
                //计算距离
                var currentPoint = new Point(e.Position.Location.Longitude, e.Position.Location.Latitude);
                if (beforePoint != new Point(0, 0))
                {
                    sportModel.Distance += GetDistance(currentPoint.Y, currentPoint.X, beforePoint.Y, beforePoint.X);
                }

                //记录点
                var foot = new SportFootModel()
                {
                    Longitude = currentPoint.X,
                    Latitude = currentPoint.Y,
                    SportId = sportModel.Id,
                    TimePoint = DateTime.Now,
                    Speed = speed
                };
                feetDB.SportFoot.InsertOnSubmit(foot);
                beforePoint = currentPoint;
            }
        }

        private static double rad(double d)
        {
            return d * Math.PI / 180.0;
        }

        public static double GetDistance(double lat1, double lng1, double lat2,
                double lng2)
        {
            double EARTH_RADIUS = 6378.137;
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double a = radLat1 - radLat2;
            double b = rad(lng1) - rad(lng2);
            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
            Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }


        //开始
        private void SportRunButton_Start(object sender, EventArgs e)
        {
            if (timer != null && geo != null)
            {
                pauseTime = DateTime.Now - DateTime.MinValue - pauseTime;//获取暂停时间
                startTime += pauseTime;//重置开始时间
                geo.Start();
                timer.Start();
            }
        }

        //结束
        private void SportRunButton_End(object sender, EventArgs e)
        {
            try
            {
                sportModel.GetAverageSpeed();
                feetDB.Sports.InsertOnSubmit(sportModel);
                feetDB.SubmitChanges();
                RunInitial();
                NavigationService.Navigate(new Uri("/Views/RunHistory.xaml", UriKind.Relative));

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

        //结束跑步
        private void RunInitial()
        {
            if (geo != null) geo.Dispose();
            geo = null;
            if (timer != null) timer.Stop();
            timer = null;

            if (feetDB != null)
            {
                feetDB.Dispose();
                feetDB = null;
            }
            feetDB = new MyRunDataContent();
            txtTimeHour.Text = "0";
            txtTimeMinuter.Text = "0";
            txtTimeSecond.Text = "0";
            txtDistance.Text = "0公里";
            txtSpeed.Text = "0公里/小时";
            txtCalorie.Text = "0Cal";
            btnSportRunButton.Initial();
            txtGPS.Text = "位置服务已初始化！";
            txtGPS.Foreground = BrushRed;

        }

        //暂停
        private void SportRunButton_Pause(object sender, EventArgs e)
        {
            pauseTime = DateTime.Now - DateTime.MinValue;//获取暂停时间起始点
            if (geo != null)
            {
                geo.Stop();
                txtGPS.Text = "位置服务已暂停！";
                txtGPS.Foreground = BrushRed;
            }

            if (timer != null)
            {
                timer.Stop();
            }

        }

        //设置
        private void btnSetting_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Setting.xaml", UriKind.Relative));
        }

        //关于
        private void btnAbout_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/About.xaml", UriKind.Relative));
        }

        //跑步记录
        private void btnSportHistory_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/RunHistory.xaml", UriKind.Relative));
        }

        //帮助
        private void btnHelper_Click(object sender, EventArgs e)
        {
            ApproachHelper.ShowApproach(() =>
            {
                this.ApplicationBar.IsVisible = true;
            });
            this.ApplicationBar.IsVisible = false;
        }

        //留言板
        private void btnMessage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Message.xaml", UriKind.Relative));
        }

    }
}